package web.mails;

import domain.entities.ComiteEtica;
import services.MailService;
import web.CommonUtils;
import domain.entities.Mail;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: vgonzalez
 * Date: 13/11/12
 * Time: 16:30
 * To change this template use File | Settings | File Templates.
 */
public class ComiteEticaMails extends MailUtils {
    private static final String ADDRESS_FROM_COMITE_ETICA = "mail.probando@yahoo.com";
    private static final String PASS_FROM_COMITE_ETICA = "mailcandoit";
    private ComiteEtica comiteEtica;
    private MailService mailService;

    public ComiteEticaMails(ComiteEtica comiteEtica, MailService mailService){
        super(ADDRESS_FROM_COMITE_ETICA, PASS_FROM_COMITE_ETICA);
        this.comiteEtica = comiteEtica;
        this.mailService = mailService;
    }

    public boolean sendMail(File schedule, String scheduleFileName, File sop, String sopFileName){
        String newLine = CommonUtils.getNewLineString();

        String mailBody = new String("Name: " + comiteEtica.getName() + newLine);
        mailBody = mailBody + "Category: " + comiteEtica.getCategory().getName() + newLine;

        List<File> files = new ArrayList<File>();
        List<String> fileNames = new ArrayList<String>();
        if(schedule != null){
            mailBody = mailBody + "Schedule: " + scheduleFileName + newLine;
            files.add(schedule);
            fileNames.add(scheduleFileName);
        }
        if(sop != null){
            mailBody = mailBody + "SOP: " + sopFileName + newLine;
            files.add(sop);
            fileNames.add(sopFileName);
        }

        String mailSubject = new String(comiteEtica.getName());

        List<Mail> mails = mailService.findByPais(comiteEtica.getAddress().getCountry());

        if(mails.isEmpty())
            return false;
        else{
            Iterator<Mail> it = mails.iterator();
            List<String> toAddresses = new ArrayList<String>();
            while(it.hasNext()){
                toAddresses.add(it.next().getEmail());
            }
            try{
                this.sendMail(mailSubject, mailBody, toAddresses, null, files, fileNames);
                return true;
            }
            catch(Exception e){
                return false;
            }
        }
    }
}
